package com.me.study.javaCore.jndi;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;

/**
 * JNDI 学习：服务实现类
 * TODO RegistryContext: object to bind must be Remote, Reference, or Referenceable
 *
 * @author ME
 * @date   2020/5/14
 */
public class JndiServiceImpl implements Referenceable, JndiService {

    private String personName;

    @Override
    public Reference getReference() throws NamingException {
        // Reference是对象的引用，Context中存放的是Reference，为了从Reference中还原出对象实例，
        // 我们需要添加field，它们是创建对象实例的线索。在JndiService中，field是个线索。
        Reference ref = new Reference(this.getClass().getName(), JndiServiceFactory.class.getName(), null);
        // 远程对象的属性都要 添加到 Reference
        ref.add(new StringRefAddr(this.getClass().getDeclaredFields()[0].getName(), this.getPersonName()));
        return ref;
    }

    @Override
    public String fun() {
        System.out.println("test fun from jndi. personName: " + personName);
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public String getPersonName() {
        return personName;
    }
}
